﻿//-----------------------------------------------------------------------
// <copyright file="MainPage.xaml.cs" company="Microsoft Corporation">
//     Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
// </copyright>
//-----------------------------------------------------------------------

namespace vsarFlightPlan.BackgroundTasks
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Windows.ApplicationModel.Background;

    internal static class Utilities
    {
        internal static void AttachTask(string taskName, Action<BackgroundTaskRegistration, BackgroundTaskCompletedEventArgs> OnCompleted)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == taskName)
                {
                    task.Value.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
                }
            }
        }

        internal async static Task RegisterTask(string taskName, string entryPoint, IEnumerable<IBackgroundTrigger> triggers, IEnumerable<IBackgroundCondition> conditions)
        {
            if (IsRegistered(taskName))
            {
                return;
            }

            var builder = new BackgroundTaskBuilder();

            builder.Name = taskName;
            builder.TaskEntryPoint = entryPoint;
            foreach (var item in triggers)
            {
                if (item.GetType() == typeof(TimeTrigger))
                {
                    try
                    {
                        var result = await BackgroundExecutionManager.RequestAccessAsync();
                        if (result == BackgroundAccessStatus.Denied)
                        {
                            return;
                        }
                    }
                    catch (Exception)
                    {
                        return;
                    }
                }

                builder.SetTrigger(item);
            }

            foreach (var item in conditions)
            {
                builder.AddCondition(item);
            }

            builder.Register();
        }

        private static bool IsRegistered(string taskName)
        {
            foreach (var task in BackgroundTaskRegistration.AllTasks)
            {
                if (task.Value.Name == taskName)
                {
                    return true;
                }
            }

            return false;
        }
    }
}